"-----------------------------------------------------------------
" 获取当前系统类型
"------------------------------------------------------------------
function! MySys()
  if has("win16") || has("win32") || has("win64") || has("win95")
    return "windows"
  elseif has("unix")
    return "linux"
  endif
endfunction
" 设置字体 以及中文支持
if has("win32")
  set guifont=Inconsolata:h12:cANSI
endif

" 配置多语言环境
if has("multi_byte")
  " UTF-8 编码
  set encoding=utf-8
  set termencoding=utf-8
  set formatoptions+=mM
  set fencs=utf-8,gbk

  if v:lang =~? '^\(zh\)\|\(ja\)\|\(ko\)'
    set ambiwidth=double
  endif

  if has("win32")
    source $VIMRUNTIME/delmenu.vim
    source $VIMRUNTIME/menu.vim
    language messages zh_CN.utf-8
  endif
else
  echoerr "Sorry, this version of (g)vim was not compiled with +multi_byte"
endif

source ~/.vim/bundles.vim

" encoding dectection

" enable filetype dectection and ft specific plugin/indent
filetype plugin indent on

" enable syntax hightlight and completion
syntax on

"解决vim语法高亮且一行代码很长卡顿
"关掉语法高亮——流畅无比>_>
"
"--------
" Vim UI
"--------
" color scheme
set background=dark
"colorscheme monokai
colorscheme vividchalk
"color solarized
"language config {
set langmenu=zh_CN.UTF-8
set helplang=cn
"show chinese help
if version >= 603
    set helplang=cn
    set encoding=utf-8
endif
"}

"highlight current line
"au WinLeave * set nocursorline nocursorcolumn
"au WinEnter * set cursorline cursorcolumn
"set cursorline cursorcolumn

" search
set incsearch
"set highlight 	" conflict with highlight current line
set hls "搜索时高亮
set ignorecase
set smartcase

" editor settings
set relativenumber    " 相对行号
set history=1000
set nocompatible
set nofoldenable                                                  " disable folding"
set confirm                                                       " prompt when existing from an unsaved file
set backspace=indent,eol,start                                    " More powerful backspacing
set t_Co=256                                                      " Explicitly tell vim that the terminal has 256 colors "
"set lbr
"不在单词中间断行。设置了这个选项后，如果一行文字非常长，无法在一行内显示完的话，它会在单词与单词间的空白处断开，尽量不会把一个单词分成两截放在两个不同的行里。
"set mouse=a                                                       " use mouse in all modes
set report=0                                                      " always report number of lines changed                "
set nowrap                                                        " dont wrap lines
"这个设置每行行最大长度
"set textwidth=86
set scrolloff=5                                                   " 5 lines above/below cursor when scrolling
set number                                                        " show line numbers
set showmatch                                                     " show matching bracket (briefly jump)
set showcmd                                                       " show typed command in status bar
set title                                                         " show file in titlebar
set laststatus=2                                                  " use 2 lines for the status bar
set matchtime=2                                                   " show matching bracket for 0.2 seconds
set matchpairs+=<:>                                               " specially for html
" set relativenumber

" Default Indentation
set autoindent
set smartindent     " indent when
set tabstop=4       " tab width
set softtabstop=4   " backspace
set shiftwidth=4    " indent width
" set textwidth=79
" set smarttab
set expandtab       " expand tab to space


"dictionary config {
"加了这句就才可以用字典补全
"补全时要双击tab才行，比较烦
set complete-=k complete+=k

au FileType php setlocal dict+=~/.vim/dict/php_funclist.dict
au FileType c setlocal dict+=~/.vim/dict/c.dict
au FileType cpp setlocal dict+=~/.vim/dict/cpp.dict
au FileType scale setlocal dict+=~/.vim/dict/scale.dict
au FileType javascript setlocal dict+=~/.vim/dict/javascript.dict
au FileType css setlocal dict+=~/.vim/dict/css.dict
au FileType html setlocal dict+=~/.vim/dict/javascript.dict
au FileType html setlocal dict+=~/.vim/dict/css.dict
au Filetype python setlocal dict+=~/.vim/dict/python.dict
"}

"输入法{
:let g:vimim_map='c-/'
":let g:vimim_cloud='sougou' " QQ云输入
:let g:vimim_punctuation=0  " 不用中文标点
:set pastetoggle=<C-H>
:let g:vimim_cloud=-1
"}
"
"自动缩进 {
autocmd FileType php setlocal tabstop=2 shiftwidth=2 softtabstop=2 textwidth=120
autocmd FileType ruby setlocal tabstop=2 shiftwidth=2 softtabstop=2 textwidth=120
autocmd FileType coffee,javascript setlocal tabstop=2 shiftwidth=2 softtabstop=2 textwidth=120
autocmd FileType python setlocal tabstop=4 shiftwidth=4 softtabstop=4 textwidth=120
autocmd FileType html,htmldjango,xhtml,haml setlocal tabstop=2 shiftwidth=2 softtabstop=2 textwidth=0
autocmd FileType sass,scss,css setlocal tabstop=2 shiftwidth=2 softtabstop=2 textwidth=120

"}

" syntax support
autocmd Syntax javascript set syntax=jquery   " JQuery syntax support
"高亮javascript中的css和HTML
let javascript_enable_domhtmlcss = 1

" js
let g:html_indent_inctags = "html,body,head,tbody"
let g:html_indent_script1 = "inc"
let g:html_indent_style1 = "inc"

"=================================
"保存时删除行末空格快捷键——空格
nmap <leader><Space><Space> :%s/\s\+$//<cr>
"python 删除行末空格
autocmd BufWritePre * :%s/\s\+$//ge
"" whitespace  去除文件的行尾空，已被上面的正则替代 {
"调用插件vim-trailling-whiterspace去除行尾空白
"autocmd BufWritePre     *.py        call WhitespaceStripTrailing()
"autocmd BufWritePre     *.h         call WhitespaceStripTrailing()
"autocmd BufWritePre     *.c         call WhitespaceStripTrailing()
"autocmd BufWritePre     *.cpp       call WhitespaceStripTrailing()
"}
"=================================
"=================================

"-----------------
" Plugin settings
"-----------------
" Rainbow parentheses for Lisp and variants
let g:rbpt_colorpairs = [
            \ ['brown',       'RoyalBlue3'],
            \ ['Darkblue',    'SeaGreen3'],
            \ ['darkgray',    'DarkOrchid3'],
            \ ['darkgreen',   'firebrick3'],
            \ ['darkcyan',    'RoyalBlue3'],
            \ ['darkred',     'SeaGreen3'],
            \ ['darkmagenta', 'DarkOrchid3'],
            \ ['brown',       'firebrick3'],
            \ ['gray',        'RoyalBlue3'],
            \ ['black',       'SeaGreen3'],
            \ ['darkmagenta', 'DarkOrchid3'],
            \ ['Darkblue',    'firebrick3'],
            \ ['darkgreen',   'RoyalBlue3'],
            \ ['darkcyan',    'SeaGreen3'],
            \ ['darkred',     'DarkOrchid3'],
            \ ['red',         'firebrick3'],
            \ ]
let g:rbpt_max = 16
autocmd Syntax lisp,scheme,clojure,racket RainbowParenthesesToggle

" tabbar
let g:Tb_MaxSize = 2
let g:Tb_TabWrap = 1

hi Tb_Normal guifg=white ctermfg=white
hi Tb_Changed guifg=green ctermfg=green
hi Tb_VisibleNormal ctermbg=252 ctermfg=235
hi Tb_VisibleChanged guifg=green ctermbg=252 ctermfg=white

" easy-motion
let g:EasyMotion_leader_key = '<Leader>'

let g:html_indent_inctags = "html,body,head,tbody"
let g:html_indent_script1 = "inc"
let g:html_indent_style1 = "inc"

"latex-preview
"每隔s自动刷新，点击<C-S-F12>
autocmd Filetype tex setl updatetime=2
let g:livepreview_previewer = 'evince'


" Tagbar
let g:tagbar_left=1
let g:tagbar_width=30
let g:tagbar_autofocus = 1
let g:tagbar_sort = 0
let g:tagbar_compact = 1
" tag for coffee
if executable('coffeetags')
    let g:tagbar_type_coffee = {
                \ 'ctagsbin' : 'coffeetags',
                \ 'ctagsargs' : '',
                \ 'kinds' : [
                \ 'f:functions',
                \ 'o:object',
                \ ],
                \ 'sro' : ".",
                \ 'kind2scope' : {
                \ 'f' : 'object',
                \ 'o' : 'object',
                \ }
                \ }

    let g:tagbar_type_markdown = {
                \ 'ctagstype' : 'markdown',
                \ 'sort' : 0,
                \ 'kinds' : [
                \ 'h:sections'
                \ ]
                \ }
endif

" Nerd Tree
let NERDChristmasTree=0
let NERDTreeWinSize=25
let NERDTreeChDirMode=2
let NERDTreeIgnore=['\~$', '\.pyc$', '\.swp$']
" let NERDTreeSortOrder=['^__\.py$', '\/$', '*', '\.swp$',  '\~$']
let NERDTreeShowBookmarks=1
let NERDTreeWinPos = "left"

" nerdcommenter
let NERDSpaceDelims=1
" nmap <D-/> :NERDComToggleComment<cr>
let NERDCompactSexyComs=1

" ZenCoding
let g:user_emmet_expandabbr_key='<C-j>'

" powerline
"let g:Powerline_symbols = 'fancy'
"
"syntastic config {
"let g:syntastic_check_on_open=1
"let g:syntastic_html_tidy_ignore_errors=[" proprietary attribute \"ng-"]
"let g:syntastic_always_populate_loc_list = 1
"let g:syntastic_auto_loc_list = 1
"let g:syntastic_check_on_wq = 0
"set statusline+=%#warningmsg#
"set statusline+=%{SyntasticStatuslineFlag()}
"set statusline+=%*
" }

" NeoComplCache
let g:neocomplcache_enable_at_startup=1
let g:neoComplcache_disableautocomplete=1
let g:neocomplcache_enable_underbar_completion = 1
let g:neocomplcache_enable_camel_case_completion = 1
let g:neocomplcache_enable_smart_case=1
let g:neocomplcache_min_syntax_length = 3
let g:neocomplcache_lock_buffer_name_pattern = '\*ku\*'
set completeopt-=preview,longest,meau

imap <C-k> <Plug>(neocomplcache_snippets_force_expand)
smap <C-k> <Plug>(neocomplcache_snippets_force_expand)
imap <C-l> <Plug>(neocomplcache_snippets_force_jump)
smap <C-l> <Plug>(neocomplcache_snippets_force_jump)

" Enable omni completion.
autocmd FileType css setlocal omnifunc=csscomplete#CompleteCSS
autocmd FileType html,markdown setlocal omnifunc=htmlcomplete#CompleteTags
autocmd FileType javascript setlocal omnifunc=javascriptcomplete#CompleteJS
autocmd FileType python setlocal omnifunc=pythoncomplete#Complete
autocmd FileType c setlocal omnifunc=ccomplete#Complete
autocmd FileType php set omnifunc=phpcomplete#CompletePHP
autocmd FileType ruby setlocal omnifunc=rubycomplete#Complete
autocmd FileType ada setlocal omnifunc=adacomplete#Complete
autocmd FileType css setlocal omnifunc=csscomplete#CompleteCSS
autocmd FileType xml setlocal omnifunc=xmlcomplete#CompleteTags
autocmd FileType sql setlocal omnifunc=sqlcomplete#Complete
" 关于Java自动文件补全插件
autocmd Filetype java setlocal omnifunc=javacomplete#Complete
"autocmd Filetype java setlocal completefunc=javacomplete#CompleteParamsInf
" " 在VIM编辑java文件时当敲入 . 时会出发,不好用
"autocmd Filetype java,javascript,jsp inoremap   .  .
"autocmd Filetype java,javascript,jsp inoremap   .  .  "

if !exists('g:neocomplcache_omni_patterns')
    let g:neocomplcache_omni_patterns = {}
endif
let g:neocomplcache_omni_patterns.erlang = '[a-zA-Z]\|:'

" SuperTab
let g:SuperTabDefultCompletionType='context'
let g:SuperTabDefaultCompletionType = '<C-X><C-U>'
let g:SuperTabRetainCompletionType=2
"
"youcomplete
"let g:ycm_global_ycm_extra_conf = 'your path to .ycm_extra_conf.py'
"let g:ycm_global_ycm_extra_conf = '~/.vim/bundle/YouCompleteMe/cpp/ycm/.ycm_extra_conf.py'
"let g:ycm_collect_identifiers_from_tags_files = 1
"let g:ycm_collect_identifiers_from_comments_and_strings = 1
"let g:syntastic_ignore_files=[".*\.py$"]
"let g:ycm_seed_identifiers_with_syntax = 1
"let g:ycm_complete_in_comments = 1
"let g:ycm_confirm_extra_conf = 0
"let g:ycm_global_ycm_extra_conf='~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp/ycm/.ycm_extra_conf.py'


" ctrlp
set wildignore+=*/tmp/*,*.so,*.o,*.a,*.obj,*.swp,*.zip,*.pyc,*.pyo,*.class,.DS_Store  " MacOSX/Linux
let g:ctrlp_custom_ignore = '\v[\/]\.(git|hg|svn)$'
let g:ctrlp_custom_ignore = '\v\.(exe|so|dll)$'
let g:ctrlp_extensions = ['funky']

let NERDTreeIgnore=['\.pyc']
"
if has("autocmd")
    autocmd BufReadPost *
                \ if line("'\"") > 0 && line("'\"") <= line("$") |
                \   exe "normal g`\"" |
                \ endif
endif"`">"'")"'")
"
" Keybindings for plugin toggle {
" Latex-Preview
nmap <C-S-F12> :LLPStartPreview<cr>
nnoremap <F2> :set invpaste paste?<CR>
set pastetoggle=<F2>
nmap <F8> :TagbarToggle<cr>
nmap <F9> :NERDTreeToggle<cr>
nmap <F3> :GundoToggle<cr>
"nmap <F4> :IndentGuidesToggle<cr>
nmap  <D-/> :
nnoremap <leader>a :Ack
nnoremap <leader>v V`]
" <F4> 开启/关闭行号显示 {
function! HideNumber()
    if(&relativenumber == &number)
        set relativenumber! number!
    elseif(&number)
        set number!
    else
        set relativenumber!
    endif
    set number?
endfunc
nnoremap <F4> :call HideNumber()<CR>
" }

"按F5编译运行{
map <F5> :call CompileRun()<CR>
func! CompileRun()
    exec "w"
    if &filetype == 'c'
        exec "!g++ % -o %<"
        exec "!time ./%<"
        exec "!rm ./%<"
    elseif &filetype == 'cpp'
        exec "!g++ % -o %<"
        exec "!time ./%<"
        exec "!rm ./%<"
    elseif &filetype == 'java'
        "exec !javac %<"
        "exec !time java %<"
        "exec !rm ./%<.class"
        "有问题，只能编译不能运行
        exec "!javac %"
        exec "!java %:r"
    elseif &filetype == 'sh'
        exec "!time bash %"
    elseif &filetype == 'python'
        exec "!time python %"
    elseif &filetype == 'html'
        exec "!chrome % &"
    elseif &filetype == 'go'
        exec "!go build %<"
        exec "!time go run %"
    elseif &filetype == 'md' "MarkDown 解决方案为VIM + Chrome浏览器的MarkDown Preview Plus插件，保存后实时预览
        exec ":!open -a /Applications/Google\ Chrome.app/ % &"
    elseif &filetype == 'javascript'
        exec "!time node %"
    elseif &filetype == 'coffee'
        exec "!time coffee %"
    elseif &filetype == 'ruby'
        exec "!time ruby %"
    endif
endfunc
"}

"代码格式优化化
map <F6> :call FormartSrc()<CR><CR>>
"定义FormartSrc()
func FormartSrc()
    exec "w"
    if &filetype == 'c'
        exec "!astyle --style=ansi -a --suffix=none %"
    elseif &filetype == 'cpp' || &filetype == 'hpp'
        exec "r !astyle --style=ansi --one-line=keep-statements -a --suffix=none %> /dev/null 2>&1"
    elseif &filetype == 'perl'
        exec "!astyle --style=gnu --suffix=none %"
    elseif &filetype == 'py'||&filetype == 'python'
        exec "r !autopep8 -i --aggressive %"
    elseif &filetype == 'java'
        exec "!astyle --style=java --suffix=none %"
    elseif &filetype == 'jsp'
        exec "!astyle --style=gnu --suffix=none %"
    elseif &filetype == 'xml'
        exec "!astyle --style=gnu --suffix=none %"
    else
        exec "normal gg=G"
        return
    endif
    exec "e! %"
endfunc
"结束定义FormartSrc

" <F7> 语法开关 {
nnoremap <F7> :exec exists('syntax_on') ? 'syn off' : 'syn on'<CR>
" Stupid shift key fixes
if !exists('g:spf13_no_keyfixes')
    if has("user_commands")
        command! -bang -nargs=* -complete=file E e<bang> <args>
        command! -bang -nargs=* -complete=file W w<bang> <args>
        command! -bang -nargs=* -complete=file Wq wq<bang> <args>
        command! -bang -nargs=* -complete=file WQ wq<bang> <args>
        command! -bang Wa wa<bang>
        command! -bang WA wa<bang>
        command! -bang Q q<bang>
        command! -bang QA qa<bang>
        command! -bang Qa qa<bang>
    endif

    cmap Tabe tabe
endif
" Ctrl + S 保存文件
" map  <C-s> <ESC>:w <CR>
" imap <C-s> <ESC>:w <CR>
" vmap <C-s> <ESC>:w <CR>
if has('win32')
  " Avoid mswin.vim making Ctrl-v act as paste
  noremap <C-V> <C-V>
endif
" " Ctrl + C 选中状态下复制
" vnoremap <C-c> "+y
"
" " Ctrl + V 粘贴剪切板中的内容
" map  <C-v> "+p
" imap <C-v> <esc>"+pa
" vmap <C-v> d"+P
"
" " 内容全选快捷键
" map <C-a> gg0vG$<cr>
" }

"snippets {
let g:UltiSnipsSnippetDirectories=["UltiSnips", "snippets"]

"}

"新建.c,.h,.sh,.java等文件，自动插入文件头
autocmd BufNewFile *.cpp,*.[ch],*.sh,*.java,*.tex,*.py exec ":call SetTitle()"
""定义函数SetTitle，自动插入文件头
func SetTitle()
    "如果文件类型为.sh文件
    if &filetype == 'sh'
        call setline(1,"\#########################################################################")
        call append(line("."), "\# File Name: ".expand("%"))
        call append(line(".")+1, "\# Author: Heathcliff")
        call append(line(".")+2, "\# mail: hrc530756164@gmail.com")
        call append(line(".")+3, "\# Created Time: ".strftime("%c"))
        call append(line(".")+4, "\#########################################################################")
        call append(line(".")+5, "\#!/bin/bash")
        call append(line(".")+6, "")
    endif
    if &filetype == 'cpp'
        call setline(1, "/*************************************************************************")
        call append(line("."), "    > File Name: ".expand("%"))
        call append(line(".")+1, "    > Author: Heathcliff")
        call append(line(".")+2, "    > Mail: hrc530756164@gmail.com ")
        call append(line(".")+3, "    > Created Time: ".strftime("%c"))
        call append(line(".")+4, " ************************************************************************/")
        call append(line(".")+5, "")
        call append(line(".")+6, "#include<iostream>")
        call append(line(".")+7, "using namespace std;")
        call append(line(".")+8, "")
    endif
    if &filetype == 'c'
        call setline(1, "/*************************************************************************")
        call append(line("."), "    > File Name: ".expand("%"))
        call append(line(".")+1, "    > Author: Heathcliff")
        call append(line(".")+2, "    > Mail: hrc530756164@gmail.com ")
        call append(line(".")+3, "    > Created Time: ".strftime("%c"))
        call append(line(".")+4, " ************************************************************************/")
        call append(line(".")+5, "#include<stdio.h>")
        call append(line(".")+6, "")
    endif
    if &filetype == 'tex'
        call setline(1, " %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
        call setline(2, " %   > File Name: ".expand("%"))
        call setline(3, " %   > Author: Heathcliff")
        call setline(4, " %   > Mail: hrc530756164@gmail.com ")
        call setline(5, " %   > Created Time: ".strftime("%c"))
        call setline(6, " %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
        call setline(7, "\\documentclass[nofonts,a4paper,12pt]{article}")
        call setline(8, "\\usepackage[urlcolor = blue, colorlinks = true, linkcolor = black]{hyperref}")
        call setline(9, "\\usepackage{graphicx} %insert graphics \\includegraphics[width]{graphics}")
        call setline(10, "\\usepackage[indentfirst]{xeCJK}")
        call setline(11, "\\usepackage{fontspec}")
        call setline(12, "\\usepackage{amsmath} %insert math expression")
        call setline(13, "\\usepackage{ctex}")
        call setline(14, "\\usepackage{listings} %\\begin{lstlisting}[language]")
        call setline(15, "\\setCJKmainfont{SimSun} %chinese fonts")
        call setline(16, "\\title{} %use preview :LLPStartPreview, shortcut:<C-S-F12>")
        call setline(17, "\\author{}")
        call setline(18, "\\date{}")
        call setline(19, "\\begin{document}")
        call setline(20, "\\maketitle")
        call setline(21, "")
    endif
    if &filetype == 'java'
        call setline(1, "//coding=utf8")
        call setline(2, "/**")
        call setline(3, "\ * @Author: Heathcliff")
        call setline(4, "\ * @Created Time : ".strftime("%c"))
        call setline(5, "")
        call setline(6, "\ * @File Name: ".expand("%"))
        call setline(7, "\ * @Description:")
        call setline(8, "")
        call setline(9, " */")
        call setline(10,"")
    endif
    if &filetype == 'python'
        call setline(1, "\#######################################################################")
        call setline(2, "\# @Author: Heathcliff")
        call setline(3, "\# @Created Time : ".strftime("%c"))
        call setline(4, "\# @File Name: ".expand("%"))
        call setline(5, "\# @Description:")
        call setline(6, "\########################################################################")
        call setline(7, "\#!/usr/bin/python")
        call setline(8, "\#coding:UTF-8")
        call setline(9, "")
    endif
    "新建文件后，自动定位到文件末尾

endfunc
autocmd BufNewFile * normal G

"texlive的相关设置,否则上面的打开.tex文件不会显示自己配置的设定
set grepprg=grep\ -nH\ $*    " 使grep总是生成文件名
let g:tex_flavor='latex'
"------------------
" Useful Functions
"------------------
" easier navigation between split windows
nnoremap <c-j> <c-w>j
nnoremap <c-k> <c-w>k
nnoremap <c-h> <c-w>h
nnoremap <c-l> <c-w>l

" When editing a file, always jump to the last cursor position
autocmd BufReadPost *
            \ if ! exists("g:leave_my_cursor_position_alone") |
            \     if line("'\"") > 0 && line ("'\"") <= line("$") |
            \         exe "normal g'\"" |
            \     endif |
            \ endif

" w!! to sudo & write a file
cmap w!! %!sudo tee >/dev/null %

" Quickly edit/reload the vimrc file
nmap <silent> <leader>ev :e $MYVIMRC<CR>
nmap <silent> <leader>sv :so $MYVIMRC<CR>

" sublime key bindings
nmap <D-]> >>
nmap <D-[> <<
vmap <D-[> <gv
vmap <D-]> >gv

"ag.vim config
let g:ag_prg="<custom-ag-path-goes-here> --vimgrep"

" for macvim
if has("gui_running")
    set go=aAce  " remove toolbar
    "set transparency=30
    set guifont=Monaco:h13
    set showtabline=2
    set columns=140
    set lines=40
    noremap <D-M-Left> :tabprevious<cr>
    noremap <D-M-Right> :tabnext<cr>
    map <D-1> 1gt
    map <D-2> 2gt
    map <D-3> 3gt
    map <D-4> 4gt
    map <D-5> 5gt
    map <D-6> 6gt
    map <D-7> 7gt
    map <D-8> 8gt
    map <D-9> 9gt
    map <D-0> :tablast<CR>
endif

